/*
 * 
 * Copyright 2011 visual-analysis-of-cancer.
 * This file is part of visual-analysis-of-cancer.
 * 
 * visual-analysis-of-cancer is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * visual-analysis-of-cancer is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with kOSMik.  If not, see <http://www.gnu.org/licenses/>.
 *  
 * visual-analysis-of-cancer:
 * An tool to analye the WHO and GLOBOCAN cancer data.
 * http://code.google.com/p/visual-analysis-of-cancer/
 * 
 * 
 * 
 * Authors: Erik Sniegula, Johannes Dahlke
 * 
 * Module:  Programming in Processing for Visual Analytics
 * Group:   20
 * 
 * Created: Aug. 2011
 * Version: 1.0
 *
 */
 




package de.fuberlin.processing.who.cancer.gui;

import java.util.Collection;
import java.util.Observable;
import java.util.Observer;
import java.util.Vector;

import processing.core.PApplet;
import processing.core.PVector;
import controlP5.Button;
import controlP5.CheckBox;
import controlP5.ControlEvent;
import controlP5.ControlGroup;
import controlP5.ControlListener;
import controlP5.ControlP5;
import controlP5.Controller;
import controlP5.ControllerGroup;
import controlP5.ControllerInterface;
import controlP5.ListBox;
import controlP5.RadioButton;
import controlP5.Slider;
import controlP5.Tab;
import controlP5.Toggle;
import de.fuberlin.processing.who.cancer.controlp5ex.MultiSelectListBox;
import de.fuberlin.processing.who.cancer.data.DBException;
import de.fuberlin.processing.who.cancer.data.Database;
import de.fuberlin.processing.who.cancer.data.DatabaseConnector;
import de.fuberlin.processing.who.cancer.data.structs.StructLocationName;
import de.fuberlin.processing.who.cancer.data.structs.StructRegionName;
import de.fuberlin.processing.who.cancer.data.structs.StructSubregionDescription;
import de.fuberlin.processing.who.cancer.interaction.CancerCauses;
import de.fuberlin.processing.who.cancer.interaction.CausesBroadcaster;
import de.fuberlin.processing.who.cancer.interaction.CausesModifier;
import de.fuberlin.processing.who.cancer.interaction.LocationBroadcaster;
import de.fuberlin.processing.who.cancer.interaction.LocationChangeSet;
import de.fuberlin.processing.who.cancer.interaction.LocationModifications;
import de.fuberlin.processing.who.cancer.interaction.LocationModifier;
import de.fuberlin.processing.who.cancer.run.CancerSketch;
import de.fuberlin.processing.who.cancer.utils.Graphics;
import de.fuberlin.processing.who.cancer.utils.Test;
import de.fuberlin.processing.who.cancer.utils.Typecast;


public class ParameterMenu extends Controller implements Observer {

	public static final int NUM_LIST_WIDTH = CancerSketch.NUM_SKETCH_WIDTH - 2
			* CancerSketch.NUM_SKETCH_PADDING;
	public static final int NUM_LIST_HEIGHT = 50;
	private LocationModifier locationModifier;
	private CausesModifier causesModifier;
	private DatabaseConnector db;
	private int left;
	private int top;
	private ControlGroup listerGroup;
	private LocationListBox locationListBox;
	private SubRegionListBox subregionListBox;
	private RegionListBox regionListBox;

	abstract class ListerBox extends MultiSelectListBox {

		public ListerBox( ControlP5 controlP5, ControllerGroup group, String name,
				int arg3, int arg4, int arg5, int arg6) {
			super( controlP5, group, name, arg3, arg4, arg5, arg6);
			setItemHeight( 15);
			setBarHeight( 15);
			PApplet p = ControlP5.papplet;
			setBackgroundColor( p.lerpColor( p.color( 0), getColor().getActive(), 0.5f));
			captionLabel().toUpperCase( true);
			captionLabel().getStyle().marginTop = 3;
			valueLabel().getStyle().marginTop = 3; 
			loadListContent();
		}

		

		protected abstract void loadListContent();

	}

	/**
	 * 
	 * Liest die Ländernamen aus der Datenbank und stellt diese in einer
	 * Dropdownliste zur Auswahl dar.
	 * 
	 * @author johannes
	 * 
	 */
	class LocationListBox extends ListerBox {

		public LocationListBox( ControlP5 controlP5, ControllerGroup group,
				String name, int arg3, int arg4, int arg5, int arg6) {
			super( controlP5, group, name, arg3, arg4, arg5, arg6);
		}


		protected void loadListContent() {
			this.clear();
			Vector<StructLocationName> locationNames = (Vector<StructLocationName>) db
					.getLocationNames();
			for ( StructLocationName locationName : locationNames) {
				addItem( locationName.locationName, locationName.locationId);
			}
		}


		@Override
		public void controlEvent( ControlEvent theEvent) {
			super.controlEvent( theEvent);
			if ( theEvent.getController() instanceof Button) {
				Vector<Integer> locationIds = new Vector<Integer>();
				for ( float f : getSelectedValues()) {
					locationIds.add( new Float( f).intValue());
				}
				locationModifier.setLocations( locationIds);
				locationModifier.update();
				Collection<Integer> locations = locationModifier.getLocations();
				regionListBox.setSelectedValues( db.getRegionsOfLocations( locations));
				subregionListBox.setSelectedValues( Typecast
						.convertCharactersToIntegers( db
								.getSubregionsOfLocations( locations)));
			}
		}

	}

	/**
	 * 
	 * Liest die WHO-Regionen aus der Datenbank und stellt diese in einer
	 * Dropdownliste zur Auswahl dar.
	 * 
	 * @author johannes
	 * 
	 */
	class RegionListBox extends ListerBox {

		public RegionListBox( ControlP5 controlP5, ControllerGroup group,
				String name, int arg3, int arg4, int arg5, int arg6) {
			super( controlP5, group, name, arg3, arg4, arg5, arg6);
		}


		protected void loadListContent() {
			this.clear();
			Vector<StructRegionName> regionNames = (Vector<StructRegionName>) db
					.getRegionNames();
			for ( StructRegionName regionName : regionNames) {
				addItem( regionName.regionName, regionName.regionId);
			}

		}


		@Override
		public void controlEvent( ControlEvent theEvent) {
			super.controlEvent( theEvent);
			if ( theEvent.getController() instanceof Button) {
				// alle bisher ausgewählten locations deselektieren
				locationModifier.clear();
				// Teste, ob mit Subregions gefiltert wird
				Collection<Character> selectedSubregions = Typecast
						.convertIntegersToCharacters( subregionListBox.getSelectedValues());
				if ( Test.isCollectionContainingElements( selectedSubregions)) {
					// dann wähle nur die Locations der Region aus,
					// die auch zu den ausgewählten Subregions gehören.
					for ( int regionId : getSelectedValues()) {
						Collection<Integer> locations = db
								.getLocationsOfRegionFilteredBySubregions( regionId,
										selectedSubregions);
						locationModifier.addLocations( locations);
					}
				} else {
					// anderenfalls wähle alle Locations der Region aus und
					// markiere alle Subregions der Region als selektiert.
					for ( int regionId : getSelectedValues()) {
						Collection<Integer> locations = db.getLocationsOfRegion( regionId);
						locationModifier.addLocations( locations);
					}
				}

				locationModifier.update();
				// update regionbox
				Collection<Integer> locations = locationModifier.getLocations();
				subregionListBox.setSelectedValues( Typecast
						.convertCharactersToIntegers( db
								.getSubregionsOfLocations( locations)));
			}
		}

	}

	/**
	 * 
	 * Liest die WHO-SubRegionen aus der Datenbank und stellt diese in einer
	 * Dropdownliste zur Auswahl dar.
	 * 
	 * @author johannes
	 * 
	 */
	class SubRegionListBox extends ListerBox {

		public SubRegionListBox( ControlP5 controlP5, ControllerGroup group,
				String name, int arg3, int arg4, int arg5, int arg6) {
			super( controlP5, group, name, arg3, arg4, arg5, arg6);
		}


		protected void loadListContent() {
			this.clear();
			Vector<StructSubregionDescription> subregionDescriptions = (Vector<StructSubregionDescription>) db
					.getSubregionDescriptions();
			for ( StructSubregionDescription subregionDescription : subregionDescriptions) {
				addItem( String.format( "%c :  %s", subregionDescription.subregionId,
						subregionDescription.subregionDescription),
						subregionDescription.subregionId);
			}
		}


		@Override
		public void controlEvent( ControlEvent theEvent) {
			super.controlEvent( theEvent);
			if ( theEvent.getController() instanceof Button) {
				// alle bisher ausgewählten locations deselektieren
				locationModifier.clear();
				// Teste, ob mit Subregions gefiltert wird
				Collection<Character> selectedSubregions = Typecast
						.convertIntegersToCharacters( getSelectedValues());
				if ( Test.isCollectionContainingElements( selectedSubregions)) {
					// dann wähle nur die Locations der Region aus,
					// die auch zu den ausgewählten Subregions gehören.
					for ( int regionId : regionListBox.getSelectedValues()) {
						Collection<Integer> locations = db
								.getLocationsOfRegionFilteredBySubregions( regionId,
										selectedSubregions);
						locationModifier.addLocations( locations);
					}
				} else {
					// anderenfalls wähle alle Locations der Region aus und
					// markiere alle Subregions der Region als selektiert.
					for ( int regionId : regionListBox.getSelectedValues()) {
						Collection<Integer> locations = db.getLocationsOfRegion( regionId);
						locationModifier.addLocations( locations);
					}
				}

				locationModifier.update();
				// update regionbox
				Collection<Integer> locations = locationModifier.getLocations();
				regionListBox.setSelectedValues( db.getRegionsOfLocations( locations));
			}
		}

	}

	class CausesSelector extends RadioButton implements Observer {

		public CausesSelector( ControlP5 controlP5, ControllerGroup group,
				String name, int left, int top) {
			super( controlP5, group, name, left, top);
			addItems();
			setItemHeight( 15);
			setBarHeight( 15);

			setBackgroundHeight( 100);
			setBarHeight( 15);
			setBackgroundColor( locationListBox.getColor().getBackground());
			setColorActive( Graphics.getColorNuance( this.getColor().getBackground(),
					170));
	
			captionLabel().toUpperCase( true);

			captionLabel().getStyle().marginTop = 3;
			valueLabel().getStyle().marginTop = 3; // the +/- sign
			showBar();
			enableCollapse();

			setItemsPerRow( 1);
			setSpacingRow( 10);
			setSpacingColumn( 10);
			setWidth( 150);

			setNoneSelectedAllowed( false);
		}


		@Override
		public void updateLayout() {
			int nn = 0;
			int xx = columnSpacing;
			int yy = rowSpacing;
			int n = _myRadioToggles.size();
			for ( int i = 0; i < n; i++) {
				Toggle t = _myRadioToggles.get( i);
				t.getPosition().y = yy;
				t.getPosition().x = xx;

				xx += t.getWidth() + columnSpacing;
				nn++;
				if ( nn == itemsPerRow) {
					nn = 0;
					_myWidth = xx;
					yy += t.getHeight() + rowSpacing;
					xx = columnSpacing;
				} else {
					_myWidth = xx;
				}
			}
		}


		protected void addItems() {
			addItem( " air pollution", CancerCauses.AIR_POLLUTION.ordinal())
					.getCaptionLabel().toUpperCase( false);
			addItem( " uv radiation", CancerCauses.UV_RADIATION.ordinal())
					.getCaptionLabel().toUpperCase( false);
			addItem( " age", CancerCauses.AGE.ordinal()).getCaptionLabel()
					.toUpperCase( false);
			addItem( " sex", CancerCauses.SEX.ordinal()).getCaptionLabel()
					.toUpperCase( false);
			// preselect air pollution
			getItem( 0).toggle();
		}


		@Override
		public void controlEvent( ControlEvent theEvent) {
			super.controlEvent( theEvent);
		  if ( theEvent.getController() instanceof Toggle) {
		  	Toggle theClickedToggle = (Toggle) theEvent.getController();
		  	CancerCauses cancerCause = CancerCauses.valueOf( new Float( theClickedToggle.internalValue()).intValue());
		    // unregister as observer to prevent endless loop
		  	causesModifier.deleteObserver( this);
		  	switch ( cancerCause) {
					case AIR_POLLUTION:
						causesModifier.setAirPollutionAsCause();
						break;
					case UV_RADIATION:
						causesModifier.setUVRadiationAsCause();
						break;
					case AGE:
						causesModifier.setAgeAsCause();
						break;
					default:
					case SEX:
						causesModifier.setSexAsCause();
						break;
				}
		  	causesModifier.addObserver( this);
		  }
		}


		@Override
		public void update( Observable observable, Object arg) {
			CancerCauses cancerCause = ( CancerCauses) arg;
	    getItem( cancerCause.ordinal()).toggle();
		}

	}


	public ParameterMenu( ControlP5 theControlP5, String theName, int theX,
			int theY) {
		super( theControlP5, (Tab) ( theControlP5.getTab( "default")), theName,
				theX, theY, NUM_LIST_WIDTH, NUM_LIST_HEIGHT);
		this.locationModifier = LocationBroadcaster.get();
		this.locationModifier.addObserver( this);
		this.causesModifier = CausesBroadcaster.get();
		
		connectToDatabase();
		initThisControl();
		initLocationListBox();
		initRegionsListBox();
		initSubRegionsListBox();
		initCausesSelector();
	}


	private void initThisControl() {
		left = new Float( this.absolutePosition.x).intValue();
		top = new Float( this.absolutePosition.y).intValue();

		listerGroup = controlP5.addGroup( "locationGroup", left, top,
				NUM_LIST_WIDTH);
		listerGroup.hideBar();

		this.getCaptionLabel().setVisible( false);
	}


	private void initLocationListBox() {
		locationListBox = new LocationListBox( controlP5, listerGroup,
				"myLocationList", 460, 20, 220, 300);
		locationListBox.actAsPulldownMenu( true);
		locationListBox.setLabel( "Locations");
	}


	private void initSubRegionsListBox() {
		subregionListBox = new SubRegionListBox( controlP5, listerGroup,
				"mySubRegionsList", 230, 20, 220, 300);
		subregionListBox.actAsPulldownMenu( true);
		subregionListBox.setLabel( "WHO Subregions");
	}


	private void initRegionsListBox() {
		regionListBox = new RegionListBox( controlP5, listerGroup, "myRegionsList",
				0, 20, 220, 300);
		regionListBox.actAsPulldownMenu( true);
		regionListBox.setLabel( "WHO Regions");
	}


	private void initCausesSelector() {
		CausesSelector causesSelector = new CausesSelector( controlP5, listerGroup,
				"myCancerCausesBox", 690, 20);
		causesSelector.setOpen( false);
		causesSelector.setLabel( "Cancer Causes");
		this.causesModifier.addObserver( causesSelector);
	}


	private void connectToDatabase() {
		try {
			db = Database.get();
		} catch ( DBException e) {
			e.printStackTrace();
		}
	}


	// overwrite the draw method for the controller's visual representation.
	public void draw( PApplet theApplet) {
		PApplet p = theApplet;
		p.pushStyle();
		p.fill( 11);
		// p.rect( left, top, width, height);
		p.popStyle();
	}


	@Override
	public Controller setValue( float theValue) {
		// TODO Auto-generated method stub
		return null;
	}


	@Override
	public void update( Observable observable, Object arg) {
		if ( observable instanceof LocationBroadcaster) {
			Collection<Integer> locations = locationModifier.getLocations();
			locationListBox.setSelectedValues( locations);
		}
	}

}
